
/*
 * pgp-pubdec.c
 *	  解密公钥加密的会话密钥。
 *
 * Copyright (c) 2005 Marko Kreen
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *	  notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *	  notice, this list of conditions and the following disclaimer in the
 *	  documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * contrib/pgcrypto/pgp-pubdec.c
 */
#include "postgres.h"

#include "pgp.h"
#include "px.h"

/*
 * 填充消息 = 02 || PS || 00 || M
 * PS - 填充值
 * M - 消息
 */
static uint8 * fc_check_eme_pkcs1_v15(uint8 *fc_data, int fc_len)
{
	uint8	   *fc_data_end = fc_data + fc_len;
	uint8	   *fc_p = fc_data;
	int			fc_rnd = 0;

	if (fc_len < 1 + 8 + 1)
		return NULL;

	if (*fc_p++ != 2)
		return NULL;

	while (fc_p < fc_data_end && *fc_p)
	{
		fc_p++;
		fc_rnd++;
	}

	if (fc_p == fc_data_end)
		return NULL;
	if (*fc_p != 0)
		return NULL;
	if (fc_rnd < 8)
		return NULL;
	return fc_p + 1;
}

/*
 * 秘密消息：1字节算法，会话密钥，2字节校验和
 * 在校验和中忽略算法
 */
static int fc_control_cksum(uint8 *fc_msg, int fc_msglen)
{
	int			fc_i;
	unsigned	fc_my_cksum,
				fc_got_cksum;

	if (fc_msglen < 3)
		return PXE_PGP_WRONG_KEY;

	fc_my_cksum = 0;
	for (fc_i = 1; fc_i < fc_msglen - 2; fc_i++)
		fc_my_cksum += fc_msg[fc_i];
	fc_my_cksum &= 0xFFFF;
	fc_got_cksum = ((unsigned) (fc_msg[fc_msglen - 2]) << 8) + fc_msg[fc_msglen - 1];
	if (fc_my_cksum != fc_got_cksum)
	{
		px_debug("pubenc cksum failed");
		return PXE_PGP_WRONG_KEY;
	}
	return 0;
}

static int fc_decrypt_elgamal(PGP_PubKey *fc_pk, PullFilter *fc_pkt, PGP_MPI **fc_m_p)
{
	int			fc_res;
	PGP_MPI    *fc_c1 = NULL;
	PGP_MPI    *fc_c2 = NULL;

	if (fc_pk->algo != PGP_PUB_ELG_ENCRYPT)
		return PXE_PGP_WRONG_KEY;

	/* 读取elgamal加密数据 */
	fc_res = pgp_mpi_read(fc_pkt, &fc_c1);
	if (fc_res < 0)
		goto out;
	fc_res = pgp_mpi_read(fc_pkt, &fc_c2);
	if (fc_res < 0)
		goto out;

	/* 解密 */ 
	fc_res = pgp_elgamal_decrypt(fc_pk, fc_c1, fc_c2, fc_m_p);

out:
	pgp_mpi_free(fc_c1);
	pgp_mpi_free(fc_c2);
	return fc_res;
}

static int fc_decrypt_rsa(PGP_PubKey *fc_pk, PullFilter *fc_pkt, PGP_MPI **fc_m_p)
{
	int			fc_res;
	PGP_MPI    *fc_c;

	if (fc_pk->algo != PGP_PUB_RSA_ENCRYPT
		&& fc_pk->algo != PGP_PUB_RSA_ENCRYPT_SIGN)
		return PXE_PGP_WRONG_KEY;

	/* 读取rsa加密数据 */
	fc_res = pgp_mpi_read(fc_pkt, &fc_c);
	if (fc_res < 0)
		return fc_res;

	/* 解密 */ 
	fc_res = pgp_rsa_decrypt(fc_pk, fc_c, fc_m_p);

	pgp_mpi_free(fc_c);
	return fc_res;
}

/* 缺少密钥ID - 用户需尝试所有密钥 */
static const uint8
			any_key[] = {0, 0, 0, 0, 0, 0, 0, 0};

int pgp_parse_pubenc_sesskey(PGP_Context *fc_ctx, PullFilter *fc_pkt)
{
	int			fc_ver;
	int			fc_algo;
	int			fc_res;
	uint8		fc_key_id[8];
	PGP_PubKey *fc_pk;
	uint8	   *fc_msg;
	int			fc_msglen;
	PGP_MPI    *fc_m;

	fc_pk = fc_ctx->pub_key;
	if (fc_pk == NULL)
	{
		px_debug("no pubkey?");
		return PXE_BUG;
	}

	GETBYTE(fc_pkt, fc_ver);
	if (fc_ver != 3)
	{
		px_debug("unknown pubenc_sesskey pkt ver=%d", fc_ver);
		return PXE_PGP_CORRUPT_DATA;
	}

	/*
	 * 检查密钥ID是否匹配 - 友好的用户消息
	 */
	fc_res = pullf_read_fixed(fc_pkt, 8, fc_key_id);
	if (fc_res < 0)
		return fc_res;
	if (memcmp(fc_key_id, any_key, 8) != 0
		&& memcmp(fc_key_id, fc_pk->key_id, 8) != 0)
	{
		px_debug("key_id's does not match");
		return PXE_PGP_WRONG_KEY;
	}

	/*
	 * 解密
	 */
	GETBYTE(fc_pkt, fc_algo);
	switch (fc_algo)
	{
		case PGP_PUB_ELG_ENCRYPT:
			fc_res = fc_decrypt_elgamal(fc_pk, fc_pkt, &fc_m);
			break;
		case PGP_PUB_RSA_ENCRYPT:
		case PGP_PUB_RSA_ENCRYPT_SIGN:
			fc_res = fc_decrypt_rsa(fc_pk, fc_pkt, &fc_m);
			break;
		default:
			fc_res = PXE_PGP_UNKNOWN_PUBALGO;
	}
	if (fc_res < 0)
		return fc_res;

	/*
	 * 提取消息
	 */
	fc_msg = fc_check_eme_pkcs1_v15(fc_m->data, fc_m->bytes);
	if (fc_msg == NULL)
	{
		px_debug("check_eme_pkcs1_v15 failed");
		fc_res = PXE_PGP_WRONG_KEY;
		goto out;
	}
	fc_msglen = fc_m->bytes - (fc_msg - fc_m->data);

	fc_res = fc_control_cksum(fc_msg, fc_msglen);
	if (fc_res < 0)
		goto out;

	/*
	 * 得到会话密钥
	 */
	fc_ctx->cipher_algo = *fc_msg;
	fc_ctx->sess_key_len = fc_msglen - 3;
	memcpy(fc_ctx->sess_key, fc_msg + 1, fc_ctx->sess_key_len);

out:
	pgp_mpi_free(fc_m);
	if (fc_res < 0)
		return fc_res;
	return pgp_expect_packet_end(fc_pkt);
}
